package com.leyou.user.service;

import com.leyou.common.utils.NumberUtils;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.pojo.User;
import com.leyou.user.utils.CodecUtils;
import org.aspectj.apache.bcel.classfile.Code;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Author: Saka
 * Date: 2019/2/21
 * Time: 20:59
 */
@Service
public class UserService {

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;


    static final String KEY_PREFIX = "user:code:phone:";

    Logger logger = LoggerFactory.getLogger(UserService.class);

    public Boolean check(String data, Integer type) {

        User record = new User();

        switch (type) {
            case 1:
                record.setUsername(data);
                break;
            case 2:
                record.setPhone(data);
                break;
            default:
                return null;

        }

        return this.userMapper.selectCount(record) != 1;

    }

    /**
     * 此处有了发送短信的需求,发送短信并不直接发送,会把消息发送给中间件
     *
     * @param phone
     * @return
     */
    public Boolean sendVerifyCode(String phone) {

        try {

            // 生成验证码
            String code = NumberUtils.generateCode(6);


            Map<String, String> info = new HashMap<>();

            info.put("phone", phone);
            info.put("code", code);

            amqpTemplate.convertAndSend("ly.sms.exchange", "sms.verify.code", info);

            redisTemplate.opsForValue().set(KEY_PREFIX + phone, code, 5, TimeUnit.MINUTES);

            return true;
        } catch (AmqpException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Boolean register(User user, String code) {

        String storeCode = redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());
        if (null!=code) {
            if (code.equals(storeCode)) {//验证码校验成功
                //保存数据

                user.setCreated(new Date());

                //生成盐值(值是随机的)
                String salt = CodecUtils.generateSalt();
                //加盐加密
                String newPassword = CodecUtils.md5Hex(user.getPassword(), salt);
                //把加密后的密码赋值给user
                user.setPassword(newPassword);
                //把盐值保存到数据库
                user.setSalt(salt);

                boolean flag = this.userMapper.insertSelective(user) == 1;

                if (flag) {
                    try {
                        this.redisTemplate.delete(storeCode);
                    } catch (Exception e) {
                        logger.error("删除缓存验证码失败,code:{}", code, e);
                    }

                }
                return flag;
            }
        }

        return null;
    }

    public User queryUser(String username, String password) {
        //查询
        User record = new User();
        record.setUsername(username);
        User user = this.userMapper.selectOne(record);
        //校验用户
        if (null == user) {
            return null;
        }
        //校验密码
        if (!user.getPassword().equals(CodecUtils.md5Hex(password, user.getSalt()))) {
            return null;
        }
        return user;
    }
}
